<?php
class News extends CActiveRecord {

    public $newsId;
    public $date;
    public $text;
    public $title;
    public $url;

    public $partners;
    public $cats;
    
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'news_data';
    }
    
    public function attributeLabels() {
        return array(
            'text' => 'Текст',
            'title' => 'Заголовок',
            'url' => 'url новости'
        );
    }
    
    public function rules() {
        return array(
            array('text, title, url', 'required', 'message'=>'{attribute} не может быть пустым'),
            array('url', 'unique', 'message'=>'{attribute} уже занят'),
            array('url', 'length', 'max'=>'64', 'tooLong'=>'Максмальная длина поля УРЛ 64'),
            array('partners, cats', 'safe')
        );
    }
    
    protected function beforeValidate() {
        if(!parent::beforeValidate()) return false;
        $this->attributes = $_POST[get_class($this)];
        return true;
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        $this->date = time();
        return true;
    }
    
    public function afterSave() {
        Yii::app()->db->createCommand()->delete('news_relation', 'newsId=:id', array(':id'=>$this->primaryKey));
        if(!empty($this->cats)) {
            if(!empty($this->partners)) {
                $cats = $this->cats;
                for($i=0; $i<count($this->cats); $i++) {
                    for($l=0; $l<count($this->partners); $l++) {
                        $data = split(',', $this->partners[$l]);
                        if($data[1] == $this->cats[$i]) {
                            Yii::app()->db->createCommand()->insert('news_relation', array('partnerid'=>$data[0], 'catId'=>$this->cats[$i], 'newsid'=>$this->getPrimaryKey()) );
                            unset($cats[$i]);
                        }
                    }
                }
                foreach ($cats as $c) 
                    Yii::app()->db->createCommand()->insert('news_relation', array('catId'=>$c, 'newsid'=>$this->getPrimaryKey() ));
            } else {
                for ($i = 0; $i<count($this->cats); $i++) 
                    Yii::app()->db->createCommand()->insert('news_relation', array('catId'=>$this->cats[$i], 'newsid'=>$this->getPrimaryKey() ));
            }
        }
    }

    public function afterDelete() {
        Yii::app()->db->createCommand()->delete('news_relation', 'newsId=:id', array(':id'=>$this->primaryKey));
        Yii::app()->db->createCommand()->delete('news_comments', 'newsId=:id', array(':id'=>$this->primaryKey));
        Yii::app()->db->createCommand()->delete('user_visits', 'typeId=:id and type="news"', array(':id'=>$this->primaryKey));
    }
}
